<?php


namespace app\common\model\mysql;


class Category extends BaseModel
{
    public $autoWriteTimestamp = true;

    /**
     * 获取分类列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllNormalList() {
        $order = [
            'list_order' => 'desc',
            'create_time' => 'desc'
        ];
        $result = $this->where('status', 'in', [0,1])->order($order)->select();
        return $result->toArray();
    }
    /**
     * 获取顶级分类
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getFirstList($num=0){
        $order = ["list_order" => "desc", "id" => "desc"];
        $where = [
            'parent_id' => 0,
            'status' => 1
        ];
        if ($num)
            $result = $this->where($where)->order($order)->limit($num)->select();
        else
            $result = $this->where($where)->order($order)->select();
        return $result->toArray();
    }

    public function getNormalList() {
        $where = [
            'status' => 1
        ];
        return $this->where($where)->select();

    }

    /**
     * 添加
     * @param $data
     * @return bool
     */
    public function add($data) {
        if (empty($data)) {
            return false;
        }
        return $this->save($data);
    }

    public function getchildrenByPid($pid) {
        $where = [
            'parent_id' => $pid,
            'status' => 1
        ];
        return $this->where($where)->select();
    }

    public function getChildrenIds($id) {
        $data = $this->getAllNormalList();
        $res = $this->_getAllChildrenIds($data, $id);
        return  $res;
    }
    public function _getAllChildrenIds($array,$id){
        $arr = [];
        foreach($array as $v){
            if($v['parent_id'] == $id){
                $arr[] = $v['id'];
                $arr = array_merge($arr, $this->_getAllChildrenIds($array,$v['id']));
            };
        };
        return $arr;
    }

}